import { useState } from "react";
import styles from "./PostImage.module.css";
import ImageViewer from "~/components/ImageViewer";
import CloseIcon from "~/components/icons/CloseIcon";

const maxHeight = "20vh";
const imgStyle = { maxHeight };

interface Props {
  src: string;
  images?: string[];
  index?: number;
  onDelete?: (index: number) => void;
  [key: string]: any;
}

export default function PostImage({
  src,
  images = [src],
  index = 0,
  onDelete,
  ...props
}: Props) {
  const [isViewerOpen, setIsViewerOpen] = useState(false);

  const wrapperStyle = {
    backgroundImage: `url('${src}')`,
    backgroundPosition: "center",
    maxHeight,
    cursor: "pointer",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    position: "relative",
  };

  const openViewer = () => {
    setIsViewerOpen(true);
  };

  const closeViewer = () => {
    setIsViewerOpen(false);
  };

  props.style = { ...wrapperStyle, ...(props.style || {}) };

  const handleDelete = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (onDelete) {
      onDelete(index);
    }
  };

  return (
    <>
      <div {...props} onClick={openViewer}>
        <img className={styles.img} style={imgStyle} src={src} />
        {onDelete && (
          <div style={{
            position: "absolute",
            top: "5px",
            right: "5px",
            backgroundColor: "rgba(0, 0, 0, 0.5)",
            borderRadius: "50%",
            width: "24px",
            height: "24px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            cursor: "pointer",
          }} onClick={handleDelete}>
            <CloseIcon width="16px" height="16px" color="white" />
          </div>
        )}
      </div>

      {isViewerOpen && (
        <ImageViewer
          images={images}
          initialIndex={index}
          onClose={closeViewer}
        />
      )}
    </>
  );
}

interface ImageGridProps {
  images: string[];
}

export function ImageGrid({ images }: ImageGridProps) {
  // 根据图片数量确定网格布局
  let gridTemplateColumns = "1fr"; // 默认一列
  if (images.length === 2) {
    // 2张图时，一行放2张
    gridTemplateColumns = "1fr 1fr";
  } else if (images.length === 3) {
    // 3张图时，一行放3张
    gridTemplateColumns = "1fr 1fr 1fr";
  } else if (images.length === 4) {
    // 4张图时，一行放2张
    gridTemplateColumns = "1fr 1fr";
  } else if (images.length > 4) {
    // 4张以上时，一行放3张
    gridTemplateColumns = "1fr 1fr 1fr";
  }

  const gridStyle = {
    display: "grid",
    gridTemplateColumns,
    gap: "0.5em",
  };

  return (
    <div style={gridStyle}>
      {images.map((image, index) => (
        <PostImage key={index} src={image} images={images} index={index} />
      ))}
    </div>
  );
}
